package com.example.library_common.album.ui

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.su_shi_tan_bas_lib.album.constant.FILE_SCAN
import com.example.library_common.album.utils.ALBUM_SELECT_REFRESH
import com.example.library_common.album.view.AlbumFolderLayout
import com.example.su_shi_tan_bas_lib.R
import com.example.su_shi_tan_bas_lib.adapter.JssBaseViewHolder
import com.example.su_shi_tan_bas_lib.album.bean.AlbumFile
import com.example.su_shi_tan_bas_lib.album.bean.AlbumFolder
import com.example.su_shi_tan_bas_lib.album.bean.FunctionBean
import com.example.su_shi_tan_bas_lib.album.constant.AlbumErrorMode
import com.example.su_shi_tan_bas_lib.album.constant.AlbumMedia
import com.example.su_shi_tan_bas_lib.album.interfaces.AlbumPanelNode
import com.example.su_shi_tan_bas_lib.album.media_reader.task.MediaTask
import com.example.su_shi_tan_bas_lib.album.ui.AlbumCameraFragment
import com.example.su_shi_tan_bas_lib.album.ui.AlbumFolderFragment
import com.example.su_shi_tan_bas_lib.album.view.AlbumFolderLayoutToggleListener
import com.example.su_shi_tan_bas_lib.base.SimpleListFragment
import com.example.su_shi_tan_bas_lib.bean.CommonBean
import com.example.su_shi_tan_bas_lib.glidmodule.GlideApp
import com.example.su_shi_tan_bas_lib.utils.PixUtils
import com.example.su_shi_tan_bas_lib.utils.decoration.GridSpacingItemDecoration
import com.example.su_shi_tan_bas_lib.utils.even.MessageWrap
import com.permissionx.guolindev.PermissionX
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type

class AlbumFragment : SimpleListFragment<AlbumFile>(), OnItemChildClickListener,
    View.OnClickListener, AlbumFolderFragment.AlbumFolderSelector {

    companion object {
        @JvmStatic
        fun newInstance(): AlbumFragment {
            val args = Bundle()
            val fragment = AlbumFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private val TAG = "AlbumFragment"

    private var funBean: FunctionBean? = null

    private val mAlbumFolderData = mutableListOf<AlbumFolder>()

    private var currentFolder = 0

    private val spanCount = 4

    private val mCheckItem = mutableListOf<AlbumFile>()

    private lateinit var albumFolderAvatar: ImageView

    private lateinit var albumFolderName: TextView

    private lateinit var albumFolderMask: AlbumFolderLayout

    private lateinit var mToolbar: Toolbar

    private lateinit var mCheckItemTextView: TextView

    private lateinit var mPreViewTextView: TextView

    private val albumFolderFragment = AlbumFolderFragment.newInstance()

    private var maxSelectedCount = FunctionBean.MIN_SELECT_COUNT

    private val mFileReScan = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            Log.d(TAG, "onReceive: ")
            when (p1?.action) {
                FILE_SCAN -> {
                    isLoaded = false
                    mCheckItem.clear()
                    mCheckItem.addAll(funBean?.checkedFiles ?: emptyList())
                    presentData()
                }
            }

        }

    }

    private val permissions = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.RECORD_AUDIO
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

//        var instance: Any = LocalBroadcastManager.getInstance(this)

        _mActivity.registerReceiver(
            mFileReScan,
            IntentFilter(FILE_SCAN)
        )

        albumFolderFragment.setAlbumFolderSelector(this)

        isEnableLoadMore = false
        isAlwaysRefresh = false
        delayedTime = 0

        val parentFragment = parentFragment

        if (parentFragment is AlbumPanelNode) {
            funBean = (parentFragment as AlbumPanelNode).functionBean
            maxSelectedCount = funBean?.selectCount ?: maxSelectedCount
        }
    }


    override fun addItemDecoration(): RecyclerView.ItemDecoration {

        return GridSpacingItemDecoration(spanCount, PixUtils.dp2px(2), true)
    }

    override fun initView(view: View) {
        super.initView(view)

        intiRootHeader()

        intiRootFooter()

        intiCenter()

        intiListHeader()

        presentData()
    }

    private fun presentData() {

        mCheckItemTextView.text =
            _mActivity.getString(R.string.album_selector, "${mCheckItem.size}/${maxSelectedCount}")
        mCheckItemTextView.isEnabled = mCheckItem.size > 0

        mPreViewTextView.text =
            _mActivity.getString(R.string.album_selector_preview, mCheckItem.size.toString())
        mPreViewTextView.isEnabled = mCheckItem.size > 0

    }

    private fun intiListHeader() {
        mAdapter.addChildClickViewIds(R.id.albumChecked)

        mAdapter.setOnItemChildClickListener(this)
        if (funBean?.isUseCamera==true){
            val header = LayoutInflater.from(_mActivity)
                .inflate(R.layout.album_fragment_list_header, rootView as ViewGroup, false)
            mAdapter.removeAllHeaderView()
            mAdapter.addHeaderView(header)

            val mCameraCover: ImageView = header.findViewById(R.id.mCameraCover)
            mCameraCover.setOnClickListener(this)
            mCameraCover.setImageResource(R.drawable.ic_album_camera)
        }

    }

    private fun intiCenter() {
        content_frame.removeAllViews()
        content_frame.visibility = View.VISIBLE
        addContentFrame(R.layout.album_fragment_folder_panel)
        albumFolderMask = content_frame.findViewById(R.id.albumFolderMask)
        albumFolderMask.setToggleListener(AlbumFolderLayoutToggleListener {

            mSwipeRefreshLayout.isEnabled = !albumFolderMask.isOnShowIng()

            albumFolderName.isSelected = albumFolderMask.isOnShowIng()
        })

        val popupMenuViews = albumFolderMask.getAlbumFolderPopupMenuViews()

        loadRootFragment(popupMenuViews.id, albumFolderFragment)
    }

    private fun intiRootHeader() {
        mHeader.removeAllViews()
        addHeader(R.layout.album_fragment_root_header)
        mToolbar = mHeader.findViewById(R.id.mToolbar)

        mToolbar.title = when (funBean?.mediaType) {
            AlbumMedia.MEDIA_FOR_IMAGE -> "相册"
            AlbumMedia.MEDIA_FOR_VIDEO -> "视频库"
            AlbumMedia.MEDIA_FOR_ALL -> "媒体库"
            else -> "文件"
        }
        mToolbar.setNavigationOnClickListener {
            this.onBackPressedSupport()
        }

        mCheckItemTextView = mHeader.findViewById(R.id.mCheckItemTextView)

        mCheckItemTextView.setOnClickListener {

            funBean?.successCallback?.onSuccess(mCheckItem)

            val parentFragment = parentFragment

            if (parentFragment is AlbumPanelNode) {
                parentFragment.finish()
            }

//            onBackPressedSupport()
        }
    }

    private fun intiRootFooter() {
        mFooter.removeAllViews()
        addFooter(R.layout.album_fragment_root_footer)
        mPreViewTextView = mFooter.findViewById(R.id.mPreViewTextView)
        albumFolderAvatar = mFooter.findViewById(R.id.albumFolderAvatar)
        albumFolderName = mFooter.findViewById(R.id.albumFolderName)
        mFooter.findViewById<View>(R.id.albumFolderLayout).setOnClickListener(this)


        mPreViewTextView.setOnClickListener {
            if (mCheckItem.isEmpty()) {
                return@setOnClickListener
            }

            val mPreviewFragment = AlbumPreviewFragment.newInstance()
            mPreviewFragment.setCurrentIndex(0)
//            mPreviewFragment.setChangedListener(object :
//                AlbumPreviewFragment.SelectedChangedListener {
//                override fun onChanged() {
//                    mCheckItem.clear()
//                    mCheckItem.addAll(funBean?.checkedFiles ?: emptyList())
//                    mAdapter.notifyDataSetChanged()
//                    presentData()
//                }
//            })
            start(mPreviewFragment)
        }
    }


    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        if(msg?.message == ALBUM_SELECT_REFRESH){
            mCheckItem.clear()
            mCheckItem.addAll(funBean?.checkedFiles ?: emptyList())
            mAdapter.notifyDataSetChanged()
            presentData()
        }
    }

    private fun loadMedia() {



        MediaTask(funBean)
            .setCallback {

                reloadData(it)
            }.execute()

    }

    private fun reloadData(it: Collection<AlbumFolder>) {
        mAlbumFolderData.clear()
        mAlbumFolderData.addAll(it)
        val albumFolder = mAlbumFolderData[currentFolder]

        loadListDate(albumFolder.albumFiles)
        val req = if (albumFolder.albumFiles.isNotEmpty())
            "file://${albumFolder.albumFiles[0].path}"
        else "file://#"

        GlideApp.with(_mActivity)
            .load(req)
            .placeholder(R.drawable.img_folder_bg_rect)
            .into(albumFolderAvatar)

        albumFolderName.text = albumFolder.name
    }


    override fun onBackPressedSupport(): Boolean {
        val parentFragment = parentFragment
        if (albumFolderMask.isOnShowIng()) {
            albumFolderMask.toggle()
//            return true
        } else if (parentFragment is AlbumPanelNode) {
            parentFragment.onBackPressed()
        }
        return true
    }

    override fun getLayoutManager(): RecyclerView.LayoutManager {
        return GridLayoutManager(_mActivity, spanCount)
    }

    override fun getItemLayout() = R.layout.album_fragment_item

    override fun convertItem(helper: JssBaseViewHolder?, item: AlbumFile?) {

        helper?.setImageLocalUrl(R.id.bg_cover, item?.path)
            ?.setViewSelect(R.id.selectedCover, containsItem(item))
            ?.setViewSelect(R.id.albumChecked, containsItem(item))


    }

    private fun containsItem(item: AlbumFile?): Boolean {
        var flag = false
        mCheckItem.forEach {
            if (it == item) {
                flag = true
            }
        }
        return flag
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .endSubType().build()
    }

    override fun netRequest() {
        PermissionX.init(_mActivity)
            .permissions(*permissions)
            .onExplainRequestReason { scope, deniedList ->
                val msg = "获取内部存储和摄像头权限"
                val positive = "确定"
                val negative = "取消"
                scope.showRequestReasonDialog(deniedList, msg, positive, negative)
            }.onForwardToSettings { scope, deniedList ->
                val msg = "获取内部存储和摄像头权限"
                val positive = "确定"
                val negative = "取消"
                scope.showForwardToSettingsDialog(deniedList, msg, positive, negative)
            }.request { allGranted, _, deniedList ->
                if (!allGranted || deniedList.isNotEmpty()) {
                    funBean?.failedCallback?.onFailed(
                        AlbumErrorMode.PERMISSION_FAILED_CODE,
                        AlbumErrorMode.PERMISSION_FAILED_MSG
                    )
                    this.onBackPressedSupport()
                } else {
                    loadMedia()
                }

            }
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        when (view.id) {
            R.id.albumChecked -> {

                val item = mAdapter.getItem(position)

                when {
                    containsItem(item) -> {
                        for (i in 0 until mCheckItem.size) {
                            val albumFile = mCheckItem[i]
                            if (albumFile == item) {
                                mCheckItem.remove(albumFile)
                                break
                            }
                        }
                    }
                    mCheckItem.size >= maxSelectedCount -> {
                        Toast.makeText(
                            _mActivity,
                            "最多选${maxSelectedCount}",
                            Toast.LENGTH_SHORT
                        ).show()

                    }
                    else -> {
                        mCheckItem.add(item)
                    }
                }
                item.isChecked = !item.isChecked
                funBean?.checkedFiles?.clear()
                funBean?.checkedFiles?.addAll(mCheckItem)
                presentData()
                val mItemPosition = position + mAdapter.headerLayoutCount
                mAdapter.notifyItemChanged(mItemPosition)
            }
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.mCameraCover -> {
                start(AlbumCameraFragment.newInstance())
//                start(AlbumCameraPanelFragment.newInstance())
            }
            R.id.albumFolderLayout -> {

                albumFolderMask.toggle()
                val newerData = mutableListOf<AlbumFolder>()
                newerData.addAll(mAlbumFolderData)
                albumFolderFragment.loadListData(newerData, currentFolder)

            }
        }
    }

    override fun onSelector(position: Int) {
        if (currentFolder == position) return
        currentFolder = position
        val newerData = mutableListOf<AlbumFolder>()
        newerData.addAll(mAlbumFolderData)
        reloadData(newerData)
        albumFolderMask.toggle()
    }

    override fun onDestroy() {
        super.onDestroy()
        _mActivity.unregisterReceiver(mFileReScan)
    }


}